<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminRole;
use App\Models\AdminRoleUser;
use App\Helpers\Common;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Exception;

class AdminController extends BaseController
{

    public function initialize(Request $request)
    {
        parent::initialize($request);

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere[] = ['status', '<>', 90];
        $this->defaultWhere = $defaultWhere;
        //$this->list_with = ['role'];

        // 角色
        $roles = AdminRole::where('status', 1)->orderBy('created_at', 'desc')->get(['id', 'name']);
        view()->share('roles', $roles);
    }

    /**
     * Profile
     */
    public function profile(Request $request)
    {
        if ($request->isMethod('post')) {
            $className = '\\App\\Models\\' . $this->model;
            $model = new $className;

            $data = $request->all();
            $adminInfo = $model->find($this->admin['id']);
            if (!$adminInfo) {
                return response()->json([
                    'code' => 0,
                    'msg' => '此用户不存在！'
                ]);
            }

            $adminInfo->name = $data['name'];
            $adminInfo->phone = $data['phone'];
            $result = $adminInfo->save();
            if ($result === false) {
                return response()->json([
                    'code' => 0,
                    'msg' => '保存失败！'
                ]);
            }

            $this->admin->name = $data['name'];
            $this->admin->phone = $data['phone'];

            return response()->json([
                'code' => 1,
                'msg' => '保存成功！'
            ]);
        }

        return view('admin/' . strtolower($this->model) . '/profile', [
            'adminInfo' => $this->admin
        ]);
    }

    /**
     * 修改密码
     */
    public function resetPassword(Request $request)
    {
        if ($request->isMethod('post')) {
            $className = '\\App\\Models\\' . $this->model;
            $model = new $className;

            $password = trim($request->input('password'));
            $newPassword = trim($request->input('newpassword'));
            $confirmPassword = trim($request->input('confirmpassword'));
            if (!$password) {
                return response()->json(['code' => 0, 'msg' => '原始密码不能为空！']);
            }
            if (!$newPassword) {
                return response()->json(['code' => 0, 'msg' => '新密码不能为空！']);
            }
            if ($newPassword != $confirmPassword) {
                return response()->json(['code' => 0, 'msg' => '两次密码不一致！']);
            }

            $adminInfo = $model->find($this->admin['id']);
            if (!$adminInfo) {
                return response()->json([
                    'code' => 0,
                    'msg' => '此用户不存在！'
                ]);
            }

            if (!Hash::check($password, $adminInfo->password)) {
                return response()->json(['code' => 0, 'msg' => '原密码不正确！']);
            }

            $adminInfo->password = Hash::make($newPassword);
            $result = $adminInfo->save();
            if ($result === false) {
                return response()->json([
                    'code' => 0,
                    'msg' => '保存失败！'
                ]);
            }

            return response()->json([
                'code' => 1,
                'msg' => '保存成功！'
            ]);
        }

        return view('admin/' . strtolower($this->model) . '/reset_password', [
            'adminInfo' => $this->admin
        ]);
    }

    /**
     * Edit
     */
    public function edit(Request $request, $id)
    {
        if ($request->isMethod('post')) {
            return $this->savePost($request);
        }

        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        $info = $model->find($id);
        $info = $model->formatItem($info, ['source' => 'backend']);

        return view('admin/' . strtolower($this->model) . '/' . $this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    protected function savePost($request)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        if ($request->post()) {
            DB::beginTransaction();
            try {
                $data = self::evalData($request);
                if ($data['password']) {
                    $data['password'] = Hash::make($data['password']);
                } else {
                    unset($data['password']);
                }
                $role_ids = $data['role_ids'];
                unset($data['confirm_password'], $data['role_ids']);

                if ($data['id']) {
                    // Update
                    $data['updated_at'] = time();
                    $result = $model->where('id', $data['id'])->update($data);

                    $msg = '保存成功!';
                    $logInfo = $this->admin->name . '更新了一条' . __($this->model) . '数据。';
                } else {
                    // Insert
                    $data['created_id'] = $data['updated_id'] = $this->admin->id;
                    $data['created_at'] = $data['updated_at'] = time();
                    $result = $model->create($data);

                    $msg = '添加成功!';
                    $logInfo = $this->admin->name . '添加了一条' . __($this->model) . '数据。';
                }

                if ($result === false) {
                    Db::rollback();
                    return response()->json([
                        'code' => 0,
                        'msg' => '保存失败'
                    ]);
                }
                if (!$data['id']) {
                    $data['id'] = $result['id'];
                }
                AdminRoleUser::where('admin_id', $data['id'])->delete();
                foreach ($role_ids as $role_id) {
                    $adminRoleRes = AdminRoleUser::create([
                        'admin_id' => $data['id'],
                        'role_id' => $role_id
                    ]);
                    if ($adminRoleRes === false) {
                        Db::rollback();
                        return response()->json([
                            'code' => 0,
                            'msg' => '添加管理员角色数据失败'
                        ]);
                    }
                }

                // 写入日志
                Common::adminLog($request, $logInfo);

                DB::commit();
                return response()->json([
                    'code' => 1,
                    'msg' => $msg
                ]);
            } catch (Exception $e) {
                Db::rollback();
                return response()->json([
                    'code' => 0,
                    'msg' => $e->getMessage()
                ]);
            }
        }
    }

    /**
     * Delete
     */
    public function delete(Request $request, $id)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        $result = $model->where('id', $id)->update(['deleted_id' => $this->admin->id, 'deleted_at' => time(), 'status' => 90]);
        if ($result === false) {
            return response()->json([
                'code' => 0,
                'msg' => '删除失败'
            ]);
        }

        // 写入日志
        $logInfo = $this->admin->name . '删除了一条' . __($this->model) . '数据。';
        Common::adminLog($request, $logInfo);

        return response()->json([
            'code' => 1,
            'msg' => '删除成功!'
        ]);
    }

    /**
     * 检查手机号是否已存在
     */
    public function checkPhone(Request $request)
    {
        $this->model = 'Admin';
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        $phone = $request->input('phone');
        $info = $model->where('status', '<>', '90')->where('phone', $phone)->select('id')->first();
        if ($info) {
            return response()->json([
                'code' => 1,
                'msg' => ''
            ]);
        } else {
            return response()->json([
                'code' => 0,
                'msg' => ''
            ]);
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        $data = $model->formatDatas($data, ['source' => 'backend']);

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $where[] = ['created_at', '>=', strtolower($rangeDate[0])];
            $where[] = ['created_at', '<=', strtotime($rangeDate[1])];
        }

        return $where;
    }
}
